import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Card, 
  Button, 
  Tag, 
  Space, 
  Modal, 
  Descriptions, 
  message,
  Input,
  Select,
  Progress,
  Divider,
  Avatar,
  Popover,
  Skeleton,
  Pagination,
  List,
  Form
} from 'antd';
import { 
  DownloadOutlined, 
  EyeOutlined, 
  SearchOutlined,
  UserOutlined,
  StarOutlined,
  StarFilled,
  LikeOutlined,
  DislikeOutlined,
  DeleteOutlined,
  CommentOutlined
} from '@ant-design/icons';
import { useDispatch } from 'react-redux';
import { fetchTorrentList, fetchUserProfile, followUser, deFollowUser,downloadTorrent ,fetchComments,
    addComment,
    likeComment,
    deleteComment} from '../../store/modules/userStore';
import './torrentList.css';
import { RouterAuth } from "../../router/routerAuth";

const { Option } = Select;
const {TextArea} = Input;

const TorrentList = () => {
  const dispatch = useDispatch();
  const [data, setData] = useState({ list: [], total: 0 });
  const [loading, setLoading] = useState(false);
  const [selectedTorrent, setSelectedTorrent] = useState(null);
  const [uploaderInfo, setUploaderInfo] = useState(null);
  const [uploaderLoading, setUploaderLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [searchParams, setSearchParams] = useState({
    id: '',
    page: 1,
    size: 10,
    categoryId: undefined 
  });
  const currentUserId = localStorage.getItem('userId');
  const passKey = localStorage.getItem('passKey');
 
    const [commentLoading, setCommentLoading] = useState(false);
    const [commentPage, setCommentPage] = useState(1);
    const [commentContent, setCommentContent] = useState('');
    const [commentUsers, setCommentUsers] = useState({});
    const [commentList, setCommentList] = useState({
  list: [],
  total: 0,
  currentPage: 1,  // 当前页码
  pageSize: 5,     // 每页显示数量
  hasNextPage: false // 是否有下一页
});

  // 分类选项
  const categories = [
    { id: 1, name: '电影' },
    { id: 2, name: '电视剧' },
    { id: 3, name: '动漫' },
    { id: 4, name: '音乐' },
    { id: 5, name: '游戏' },
    { id: 6, name: '软件' },
    { id: 7, name: '纪录片' },
    { id: 8, name: '体育' },
    { id: 9, name: '电子书' },
    { id: 99, name: '其他' }
    
  ];

  // 获取种子列表
  const fetchData = () => {
    setLoading(true);
    dispatch(fetchTorrentList(searchParams))
      .then(res => {
        if (res && res.code === 0) {
          setData(res.data || { list: [], total: 0 });
        } else {
          message.error(res?.msg || '获取种子列表失败');
        }
      })
      .catch(err => {
        console.error('获取种子列表错误:', err);
        message.error('获取种子列表出错');
      })
      .finally(() => {
        setLoading(false);
      });
  };
 // 获取单个用户信息并缓存
const getUserInfo = async (userId) => {
  try {
    const res = await dispatch(fetchUserProfile(userId));
    if (res && res.code === 0) {
      setCommentUsers(prev => ({
        ...prev,
        [userId]: res.data
      }));
    }
  } catch (err) {
    console.error('获取用户信息失败:', err);
  }
};
  const fetchCommentsList = async (page = 1) => {
  if (!selectedTorrent) return;
  
  setCommentLoading(true);
  
  try {
    const res = await dispatch(fetchComments({
      page: page,
      size: 5,  // 固定每页5条
      torrentId: selectedTorrent.id
    }));
    
    if (res && res.code === 0) {
      setCommentList({
        list: res.data.list || [],
        total: res.data.total || 0,
        currentPage: res.data.pageNum || 1,
        pageSize: res.data.pageSize || 5,
        hasNextPage: res.data.hasNextPage || false
      });
      
      // 获取用户信息
      res.data.list.forEach(comment => {
        if (!comment.isAnonymous && comment.userId) {
          getUserInfo(comment.userId);
        }
      });
    }
  } finally {
    setCommentLoading(false);
  }
};
    // 提交评论
    const handleCommentSubmit = () => {
        if (!selectedTorrent) return;
        if (!commentContent.trim()) {
            message.warning('评论内容不能为空');
            return;
        }

        dispatch(addComment({
            torrentId: selectedTorrent.id,
            userId: currentUserId,
            content: commentContent,
            isAnonymous: false
        }))
            .then(res => {
                if (res && res.code === 0) {
                    message.success('评论提交成功');
                    setCommentContent('');
                    // 刷新评论列表
                    fetchCommentsList();
                } else {
                    message.error(res?.msg || '提交评论失败');
                }
            })
            .catch(err => {
                console.error('提交评论错误:', err);
                message.error('提交评论出错');
            });
    };

    // 点赞评论
    const handleLikeComment = (commentId) => {
        dispatch(likeComment({id: commentId}))
            .then(res => {
                if (res && res.code === 0) {
                    // 更新评论列表中的点赞数和isLike状态
                    setCommentList(prev => ({
                        ...prev,
                        list: prev.list.map(comment =>
                            comment.id === commentId ?
                                {...comment, 
                                 likes: comment.likes + (comment.isLike ? -1 : 1),
                                 isLike: !comment.isLike
                                } :
                                comment
                        )
                    }));
                } else {
                    message.error(res?.msg || '点赞失败');
                }
            })
            .catch(err => {
                console.error('点赞评论错误:', err);
                message.error('点赞评论出错');
            });
    };

    // 删除评论
    const handleDeleteComment = (commentId) => {
        Modal.confirm({
            title: '确认删除',
            content: '确定要删除这条评论吗？',
            onOk: () => {
                dispatch(deleteComment({id: commentId}))
                    .then(res => {
                        if (res && res.code === 0) {
                            message.success('评论删除成功');
                            // 刷新评论列表
                            fetchCommentsList(commentList.currentPage);
                        } else {
                            message.error(res?.msg || '删除评论失败');
                        }
                    })
                    .catch(err => {
                        console.error('删除评论错误:', err);
                        message.error('删除评论出错');
                    });
            }
        });
    };

   const handlePageChange2 = (page) => {
  fetchCommentsList(page);
};

    // 当选中种子变化时加载第一页评论
useEffect(() => {
  if (selectedTorrent) {
    fetchCommentsList(1); // 总是从第一页开始加载
    setCommentPage(1);    // 重置页码状态
  }
}, [selectedTorrent]);

  // 获取上传者信息
  const fetchUploaderInfo = (userId) => {
    setUploaderLoading(true);
    
    dispatch(fetchUserProfile(userId))
      .then(res => {
        if (res && res.code === 0) {
          setUploaderInfo(res.data);
        } else {
          message.error(res?.msg || '获取用户信息失败');
        }
      })
      .catch(err => {
        console.error('获取用户信息错误:', err);
        message.error('获取用户信息出错');
      })
      .finally(() => {
        setUploaderLoading(false);
      });
  };

  // 处理关注/取消关注用户
  const handleFollow = async (userId, followed) => {
    try {
      const action = followed ? deFollowUser : followUser;
      const res = await dispatch(action(userId));
      console.log(res);
      
      if (res.code === 0) {
        const msg = res.data;
        message.success(msg);
        setUploaderInfo(prev => ({
          ...prev,
          followed: !followed
        }));
      } else {
        const msg = res.msg;
        message.warning(msg);
      }
    } catch (err) {
      console.error('操作错误:', err);
      message.error('网络请求失败，请稍后重试');
    }
  };

  useEffect(() => {
    fetchData();
  }, [searchParams]);

  // 格式化文件大小
  const formatSize = (bytes) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  // 处理下载
  const handleDownload = async (torrentId) => {
    try {
    const res = await dispatch(downloadTorrent({
      id: torrentId,
      passKey: passKey
    }));
    
    if (res.code === 0) {
      const downloadUrl = res.data;
      // 创建隐藏的a标签触发下载
      const link = document.createElement('a');
      link.href = downloadUrl;
      link.download = '';
      link.style.display = 'none';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      message.success('开始下载种子文件');
    } else {
      message.error(res.msg || '下载失败');
    }
  } catch (err) {
    console.error('下载错误:', err);
    message.error('下载失败');
  }
 
};

  // 显示详情
  const showDetail = (record) => {
    setSelectedTorrent(record);
    if (!record.anonymous && record.userId) {
      fetchUploaderInfo(record.userId);
    }
    setIsModalVisible(true);
  };

  // 处理分页变化
  const handlePageChange = (page, size) => {
    setSearchParams(prev => ({
      ...prev,
      page,
      size
    }));
  };

  // 处理搜索
  const handleSearch = () => {
    setSearchParams(prev => ({
      ...prev,
      page: 1 // 搜索时重置到第一页
    }));
  };

  // 重置搜索
  const handleReset = () => {
    setSearchParams({
      id: '',
      page: 1,
      size: 10,
       categoryId: undefined
    });
  };

   
    // 表格列定义
    const columns = [
        {
            title: '标题',
            dataIndex: 'title',
            key: 'title',
            render: (text, record) => (
                <div className="torrent-title">
                    <span>{text}</span>
                    {record.freeleech && (
                        <Tag color="green" style={{marginLeft: 8}}>免费</Tag>
                    )}
                </div>
            ),
        },
        {
            title: '上传者',
            dataIndex: 'userName',
            key: 'uploader',
            width: 150,
            render: (text, record) => (
                record.anonymous ? (
                    <Tag>匿名</Tag>
                ) : (
                    <Popover
                        content={
                            <div style={{padding: 8}}>
                                <Skeleton loading={uploaderLoading} active>
                                    {uploaderInfo && (
                                        <div>
                                            <p>用户名: {uploaderInfo.username}</p>
                                            <p>等级: Lv.{uploaderInfo.level}</p>
                                        </div>
                                    )}
                                </Skeleton>
                            </div>
                        }
                        trigger="hover"
                    >
                        <Tag icon={<UserOutlined/>}>{text || `用户 ${record.uploaderId}`}</Tag>
                    </Popover>
                )
            ),
        },
        {
            title: '大小',
            dataIndex: 'fileSize',
            key: 'fileSize',
            width: 120,
            render: (size) => formatSize(size),
            sorter: (a, b) => a.fileSize - b.fileSize,
        },
        {
            title: '分类',
            dataIndex: 'category',
            key: 'category',
            width: 100,
            render: (category) => (
                categories.find(c => c.id === category)?.name || '未知'
            ),
            filters: categories.map(c => ({text: c.name, value: c.id})),
            onFilter: (value, record) => record.category === value,
        },
        {
            title: '上传时间',
            dataIndex: 'uploadTime',
            key: 'uploadTime',
            width: 180,
            render: (time) => new Date(time).toLocaleString(),
            sorter: (a, b) => new Date(a.uploadTime) - new Date(b.uploadTime),
        },
        {
            title: '操作',
            key: 'action',
            width: 150,
            render: (_, record) => (
                <Space size="middle">
                    <Button
                        type="link"
                        icon={<EyeOutlined/>}
                        onClick={() => showDetail(record)}
                    >
                        详情
                    </Button>
                    <Button
                        type="link"
                        icon={<DownloadOutlined/>}
                        onClick={() => handleDownload(record.id)} // 传入种子ID
                    >
                        下载
                    </Button>
                </Space>
            ),
        }
    ];

 

  return (
    <RouterAuth>
    <div className="torrent-container">
      <Card 
        title="种子列表"
        extra={
          <Space>
            <Button onClick={handleReset}>重置</Button>
            <Button type="primary" onClick={handleSearch}>搜索</Button>
          </Space>
        }
      >
        <div className="search-bar">
          <Input
            placeholder="输入种子ID精确搜索"
            prefix={<SearchOutlined />}
            value={searchParams.id}
            onChange={(e) => setSearchParams({...searchParams, id: e.target.value})}
            style={{ width: 200, marginRight: 16 }}
          />
          <Select
  placeholder="选择分类"
  style={{ width: 120 }}
  allowClear
  value={searchParams.categoryId}
  onChange={(value) => setSearchParams({
    ...searchParams,
    categoryId: value || undefined, // 清空时设为undefined
    page: 1 // 切换分类时重置到第一页
  })}
>
  {categories.map(category => (
    <Option key={category.id} value={category.id}>{category.name}</Option>
  ))}
</Select>
        </div>

        <Table
          columns={columns}
          dataSource={data.list}
          rowKey="id"
          loading={loading}
          pagination={false}
        />

        <div style={{ marginTop: 16, textAlign: 'right' }}>
          <Pagination
            current={searchParams.page}
            pageSize={searchParams.size}
            total={data.total}
            onChange={handlePageChange}
            showSizeChanger
            showQuickJumper
            showTotal={total => `共 ${total} 条`}
          />
        </div>
      </Card>

      {/* 详情模态框 */}
      <Modal
        title="种子详情"
        width={800}
        visible={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={[
          <Button 
            key="download" 
            type="primary" 
            icon={<DownloadOutlined />}
            onClick={() => selectedTorrent && handleDownload(selectedTorrent.id)}
          >
            下载种子
          </Button>,
          <Button key="close" onClick={() => setIsModalVisible(false)}>
            关闭
          </Button>
        ]}
      >
        {selectedTorrent && (
          <>
            <Descriptions bordered column={2}>
              <Descriptions.Item label="标题" span={2}>
                {selectedTorrent.title}
                {selectedTorrent.freeleech && (
                  <Tag color="green" style={{ marginLeft: 8 }}>免费</Tag>
                )}
              </Descriptions.Item>
              <Descriptions.Item label="描述">{selectedTorrent.description}</Descriptions.Item>
              <Descriptions.Item label="IMDb链接">
                {selectedTorrent.imdbLink ? (
                  <a href={selectedTorrent.imdbLink} target="_blank" rel="noreferrer">
                    {selectedTorrent.imdbLink}
                  </a>
                ) : '无'}
              </Descriptions.Item>
              <Descriptions.Item label="文件大小">{formatSize(selectedTorrent.fileSize)}</Descriptions.Item>
              <Descriptions.Item label="文件数量">{selectedTorrent.fileCount}</Descriptions.Item>
              <Descriptions.Item label="分类">
                {categories.find(c => c.id === selectedTorrent.category)?.name || '未知'}
              </Descriptions.Item>
              <Descriptions.Item label="语言">{selectedTorrent.language || '无'}</Descriptions.Item>
              <Descriptions.Item label="字幕信息">{selectedTorrent.subtitleInfo || '无'}</Descriptions.Item>
              <Descriptions.Item label="上传时间">
                {new Date(selectedTorrent.uploadTime).toLocaleString()}
              </Descriptions.Item>
              <Descriptions.Item label="促销状态">
                <Tag color="orange">{selectedTorrent.promotionStatus}</Tag>
                <div style={{ marginTop: 8 }}>
                  <Progress 
                    percent={selectedTorrent.uploadMultiplier * 50} 
                    format={() => `${selectedTorrent.uploadMultiplier}X上传`}
                    status="active"
                  />
                  <Progress 
                    percent={selectedTorrent.downloadDiscount === '100%' ? 100 : 50} 
                    format={() => `${selectedTorrent.downloadDiscount}下载`}
                    status="active"
                  />
                </div>
              </Descriptions.Item>
              <Descriptions.Item label="InfoHash" span={2}>
                <code>{selectedTorrent.infoHash}</code>
              </Descriptions.Item>
            </Descriptions>

            {!selectedTorrent.anonymous && selectedTorrent.uploaderId && (
              <>
                <Divider orientation="left">上传者信息</Divider>
                <Card loading={uploaderLoading}>
                  {uploaderInfo && (
                    <div className="uploader-info">
                      <div className="uploader-avatar">
                        <Avatar 
                          size={64} 
                          src={uploaderInfo.avatar} 
                          icon={<UserOutlined />}
                        />
                        {uploaderInfo.userId !== currentUserId && (
                          <Button 
                            type="text" 
                            icon={uploaderInfo.followed ? <StarFilled /> : <StarOutlined />}
                            onClick={() => handleFollow(uploaderInfo.userId, uploaderInfo.followed)}
                          >
                            {uploaderInfo.followed ? '已关注' : '关注'}
                          </Button>
                        )}
                      </div>
                      <div className="uploader-details">
                        <h3>{uploaderInfo.username}</h3>
                        <p>等级: Lv.{uploaderInfo.level}</p>
                        <p>注册日期: {uploaderInfo.registrationDate}</p>
                        <p>上传量: {formatSize(uploaderInfo.uploadedDelta * 1024 * 1024 * 1024)}</p>
                      </div>
                    </div>
                  )}
                </Card>
              </>
            )}
            {/* 评论区 */}
                        <Divider orientation="left">
                            评论区 <Tag color="blue">{commentList.total} 条评论</Tag>
                        </Divider>

                        {/* 评论输入框 */}
                        <Card className="comment-input-card">
                            <Form.Item>
                                <TextArea // 修正为 TextArea
                                    rows={4}
                                    placeholder="分享你的观点..."
                                    value={commentContent}
                                    onChange={(e) => setCommentContent(e.target.value)}
                                    onPressEnter={handleCommentSubmit}
                                />
                            </Form.Item>
                            <Form.Item>
                                <Button
                                    type="primary"
                                    onClick={handleCommentSubmit}
                                    disabled={!commentContent.trim()}
                                    icon={<CommentOutlined/>}
                                >
                                    发表评论
                                </Button>
                            </Form.Item>
                        </Card>

                  
                       {/* 评论列表 */}
                        <List
                          className="comment-list"
                          itemLayout="horizontal"
                          dataSource={commentList.list}
                          loading={commentLoading}
                          renderItem={(item) => (
                            <List.Item>
                              <List.Item.Meta
                                avatar={
                                  item.isAnonymous ? (
                                    <Avatar icon={<UserOutlined />} />
                                  ) : (
                                    <Avatar 
                                      src={commentUsers[item.userId]?.avatar} 
                                      icon={<UserOutlined />}
                                    />
                                  )
                                }
                                title={
                                  item.isAnonymous ? 
                                    "匿名用户" : 
                                    (commentUsers[item.userId]?.username || `用户 ${item.userId}`)
                                }
                                description={<p>{item.content}</p>}
                              />
                              <div>
                                <span>{item.createdAt ? new Date(item.createdAt).toLocaleString() : new Date(item.updatedAt).toLocaleString() }</span>
                                <Space>
                                  <Button 
                                    type="text" 
                                    icon={<LikeOutlined />} 
                                    onClick={() => handleLikeComment(item.id)}
                                    style={{ color: item.isLike ? '#1890ff' : undefined }}
                                  >
                                    {item.likes || 0}
                                  </Button>
                                  {!item.isAnonymous && currentUserId === String(item.userId) && (
                                    <Button 
                                      type="text" 
                                      icon={<DeleteOutlined />} 
                                      onClick={() => handleDeleteComment(item.id)}
                                      style={{ color: '#ff4d4f' }}
                                    >
                                      删除
                                    </Button>
                                  )}
                                </Space>
                              </div>
                            </List.Item>
                          )}
                        />

                        {/* 分页控件 */}
                        <div style={{ marginTop: 16, textAlign: 'center' }}>
                          <Pagination
                            current={commentList.currentPage}
                            pageSize={commentList.pageSize}
                            total={commentList.total}
                            onChange={handlePageChange2}
                            showSizeChanger={false}
                            showQuickJumper
                            showTotal={total => `共 ${total} 条评论`}
                          />
                        </div>
                          </>
                        )}
                      </Modal>
                    </div>
                    </RouterAuth>
                  );
                };

export default TorrentList;